/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javagameengine;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 *
 * @author jimi
 */
public class Keyboard implements KeyListener
{

	boolean keys[] = new boolean[256];
	boolean keys_t[] = new boolean[256];
	public static Keyboard is = new Keyboard();
	public function OnKeyTriggered = null;

	private Keyboard()
	{
		/* dumb java version of "ZeroMemory( this, sizeof(this) )" */
		int i;
		for( i = 0 ; i < keys.length ; i++ )
		{
			keys[i] = false;
			keys_t[i] = false;
		}

	}

	public boolean pressed( int keyCode )
	{
		return keys[keyCode];
	}

	public boolean released( int keyCode )
	{
		return !keys[keyCode];
	}

	public boolean triggered( int keyCode )
	{
		return keys_t[keyCode];
	}

	@Override
	public void keyTyped( KeyEvent e )
	{
		int kc;

		if( e.getID() == KeyEvent.KEY_TYPED )
		{
			kc = e.getKeyChar();
		}
		else
		{
			kc = e.getKeyCode();
		}

		OnKeyTriggered.execute( kc );

	}

	@Override
	public void keyPressed( KeyEvent e )
	{
		int kc;

		if( e.getID() == KeyEvent.KEY_TYPED )
		{
			kc = e.getKeyChar();
		}
		else
		{
			kc = e.getKeyCode();
		}

		if( !pressed( kc ) )
		{
			keys_t[kc] = true;
		}
		else
		{
			keys_t[kc] = false;
		}

		keys[kc] = true;
	}

	@Override
	public void keyReleased( KeyEvent e )
	{
		if( e.getID() == KeyEvent.KEY_TYPED )
		{
			int kc = e.getKeyChar();
			keys[kc] = false;
			keys_t[kc] = false;
		}
		else
		{
			int kc = e.getKeyCode();
			keys[kc] = false;
			keys_t[kc] = false;
		}
	}
}
